package com.yyx.server.controller;

import com.yyx.server.pojo.Admin;
import com.yyx.server.pojo.ChatMsg;
import com.yyx.server.service.AdminService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author YongXin
 * @date Created in 2021/8/16 15:06
 */
@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private AdminService adminService;

    @MessageMapping("/ws/chat")
    private void handleMsg(Authentication authentication, ChatMsg chatMsg){
        Admin admin = (Admin) authentication.getPrincipal();
        chatMsg.setFrom(admin.getUsername());
        chatMsg.setFromNickName(admin.getName());
        chatMsg.setDate(LocalDateTime.now());
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }


    @ApiOperation("获取聊天对象")
    @ResponseBody
    @GetMapping("/chat/admin")
    public List<Admin> getChatAdmin(String keywords){
        return adminService.getAllAdmins(keywords);
    }
}
